package com.saifan.wyy_ov.ui.communitycenter;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.ColletionRequestBean;
import com.saifan.wyy_ov.data.bean.ConvenienttooBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.common.BaseFragment;
import com.saifan.wyy_ov.ui.communitylife.ConvenienttooActivity;
import com.saifan.wyy_ov.ui.communitylife.ConvenienttooInfoActivity;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.utils.CallPhoneUtil;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015/6/9-21:19
 * @descrption 我的便民工具收藏
 */
public class ConvenienttooEnshrineFragment extends BaseFragment {
    private boolean isLoad=false;
    int page = 0;
    int type = 1;
    private RefreshLayout refreshLayout;
    private ListView listView;
    private List<ConvenienttooBean> beans = new ArrayList<>();
    private CommonAdapter<ConvenienttooBean> adapter;
    private View view;
    private GetData getData;
    private RelativeLayout loadlay;

    public ConvenienttooEnshrineFragment() {
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getData = new GetData();

    }

    public void query() {

        if (beans.isEmpty()){
            loadlay.setVisibility(View.VISIBLE);
        }
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("UserID", getRoomInfoBean().getWYKHDA_ZJ());
            jsonObject.put("Page", page);
            jsonObject.put("Type", type);

            getData.getDataJson(getActivity(), Api.Collection.MY_COLLECTION, jsonObject, "", new ResponseData() {
                @Override
                public void onSuccess(String json) {
                    List<ConvenienttooBean> list = new Gson().fromJson(json, new TypeToken<List<ConvenienttooBean>>() {
                    }.getType());
                    if (list!=null&&!list.isEmpty()) {
                        if (page == 0) {
                            beans = list;
                        } else {
                            beans.addAll(list);
                        }
                        adapter.mDatas = beans;
                        adapter.notifyDataSetChanged();
                        isLoad = true;
                    } else {
                        if (page > 0) {
                            page--;
                            ToastUtil.showToast(getActivity(),"暂无更多信息");
                        }else {

                            ToastUtil.showToast(getActivity(),"暂无相关信息");
                        }


                    }

                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    loadlay.setVisibility(View.GONE);

                }

                @Override
                public void onFailed(String str) {
                    loadlay.setVisibility(View.GONE);
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    if (page > 0) page--;

                }
            });
        } catch (JSONException e) {
        }
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        if (isVisibleToUser) {
            if (!isLoad) {
                query();
            }
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_message, container, false);
        this.refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        this.listView = (ListView) view.findViewById(R.id.listView);
        this.loadlay = (RelativeLayout) view.findViewById(R.id.loading_lay);
        initAdapter();
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                refreshLayout.setRefreshing(true);
                query();
            }
        });

        refreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                refreshLayout.setLoading(true);
                page++;
                query();
            }
        });


        return view;
    }

    private void initAdapter() {
        adapter = new CommonAdapter<ConvenienttooBean>(getActivity(), beans, R.layout.convenienttoo_item) {
            @Override
            public void convert(final ViewHolderHelper helper, final ConvenienttooBean item) {
                item.setBMGJ_SFYX(true);
                helper.setText(R.id.BMGJ_LXR, StringUtil.returnShow(item.getBMGJ_BT()));
                helper.setText(R.id.BMGJ_LXDH, StringUtil.returnShow(item.getBMGJ_LXDH()));
                helper.setText(R.id.BMGJ_DZ, "  " + StringUtil.returnShow(item.getBMGJ_DZ()));
                helper.setText(R.id.BMGJ_FWSM, StringUtil.returnShow(item.getBMGJ_FWSM()));
                if (type == 11) {
                    helper.getView(R.id.BMGJ_FWSM).setVisibility(View.GONE);
                } else {
                    helper.getView(R.id.BMGJ_FWSM).setVisibility(View.VISIBLE);
                }
                if (!item.isBMGJ_WYRZ()) {
                    helper.getView(R.id.sign_authentication).setVisibility(View.GONE);
                }
                helper.getView(R.id.imageView_collect_tel).setBackgroundResource(R.drawable.collect_succeed);
                ((TextView) (helper.getView(R.id.textView_collect_tel))).setText("取消收藏");
                ((TextView) (helper.getView(R.id.textView_collect_tel))).setTextColor(getResources().getColor(R.color.china_red));

                helper.getView(R.id.collect_tel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        v.setClickable(false);
                        if (item.isBMGJ_SFYX()) {
                            ColletionRequestBean colletionRequestBean = new ColletionRequestBean();
                            colletionRequestBean.setXMBS(getRoomInfoBean().getXMBS());
                            colletionRequestBean.setWDSC_KHWJ(getRoomInfoBean().getFKGX_ZJ());
                            colletionRequestBean.setWDSC_MKID(item.getBMGJ_ZJ());
                            colletionRequestBean.setWDSC_LX(1);

                            new GetData().getDataJson(getActivity(), Api.Collection.CANCEL_COLLECTION, colletionRequestBean, getString(R.string.wait), new ResponseData() {
                                @Override
                                public void onSuccess(String json) {
                                    adapter.mDatas.remove(item);
                                    adapter.notifyDataSetChanged();
                                    ToastUtil.showToast(getActivity(), "您已取消！");


                                }

                                @Override
                                public void onFailed(String str) {
                                    helper.getView(R.id.collect_tel).setClickable(true);
                                }
                            });

                        }


                    }
                });


                final String tel = item.getBMGJ_LXDH();
                helper.getView(R.id.tel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (Build.VERSION.SDK_INT >= 23) {

                            int checkCallPhonePermission = ContextCompat.checkSelfPermission( getActivity(), Manifest.permission.CALL_PHONE);
                            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
                                return;
                            } else {
                                CallPhoneUtil.callPhone( getActivity(),  tel);


                            }
                        } else {

                            CallPhoneUtil.callPhone( getActivity(), tel);

                        }
                    }
                });
                helper.getView(R.id.cardView).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent(getActivity(), ConvenienttooInfoActivity.class);
                        intent.putExtra("ConvenienttooBean", item);
                        startActivity(intent);

                    }
                });

            }
        };
        listView.setAdapter(adapter);
    }

    private static final int CALL_PHONE = 123;
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {




            } else {
                // Permission Denied
                Toast.makeText(getActivity(), "您禁用拨打电话权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }
    public static ConvenienttooEnshrineFragment newInstance() {
        ConvenienttooEnshrineFragment f = new ConvenienttooEnshrineFragment();
        return f;
    }

}
